from django.shortcuts import render
#引入student类
from student.models import Student
#引入JsonResponse模块
from django.http import JsonResponse
#导入json模块
import json
#导入uuid模块
import uuid
#导入哈希模块
import hashlib
import os
from django.conf import settings
# Create your views here.




#获取学生信息
def get_students(request):
    """获取全部学生信息"""
    try:
        obj_students=Student.objects.all().values()
        #使用ORM获取所有学生信息
        #把结果转为list
        student=list(obj_students)
        return JsonResponse({'code':1,'data':student})
    except Exception as e:
        return JsonResponse({'code':0,'msg':'获取学生信息错误。'+str(e)})

#查询学生信息
def query_students(request):
    #接受查询条件，并将接收数据解析为json
    data=json.loads(request.body.decode('utf-8'))
    #查询学生信息
    try:
        obj_students=Student.objects.filter(name__icontains=data['inputstr']).values()
        student=list(obj_students)
        return JsonResponse({'code':1,'data':student})
    except Exception as e:
        return JsonResponse({'code':0,'msg':e})
    pass

#检查学号
def is_exsits_sno(request):
    #判断接收学号
    data=json.loads(request.body.decode('utf-8'))
    obj_student = Student.objects.filter(sno=data['sno'])
    try:
        if obj_student.count()==0:
            return JsonResponse({'code':1,'exsits':False})
        else:
            return JsonResponse({'code': 1, 'exsits': True})
    except Exception as e:
        return JsonResponse({'code': 1, 'message': '校验学号失败！请联系管理员。'})

# 添加学生到数据库
def add_student(request):
    data=json.loads(request.body.decode('utf-8'))
#     添加到数据库
    try:
        obj_student=Student(sno=data['sno'],name=data['name'],gender=data['gender'],birthday=data['birthday'],
                            mobile=data['mobile'],email=data['email'],address=data['address'],image=data['image'])
        obj_student.save()
        obj_students = Student.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        student = list(obj_students)
        return JsonResponse({'code': 1, 'data': student})
    except Exception as e:
        return  JsonResponse({'code':0,'message':"添加到数据库异常，请联系管理员！"})



# 编辑学生信息
def edit_student(request):
    data=json.loads(request.body.decode('utf-8'))
    try:
        # 查找到要修改的学生信息
        obj_student = Student.objects.get(sno=data['sno'])
        # 依次修改字段
        obj_student.name=data['name']
        obj_student.gender=data['gender']
        obj_student.birthday=data['birthday']
        obj_student.mobile=data['mobile']
        obj_student.email=data['email']
        obj_student.address=data['address']
        obj_student.image=data['image']

        obj_student.save()
        obj_students = Student.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        student = list(obj_students)
        return JsonResponse({'code': 1, 'data': student})
    except Exception as e:
        return JsonResponse({'code': 0, 'message': "修改数据库异常，请联系管理员！"})

def delete_student(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 查找到要修改的学生信息
        obj_student = Student.objects.get(sno=data['sno'])
        # 删除数据
        obj_student.delete()
        obj_students = Student.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        student = list(obj_students)
        return JsonResponse({'code': 1, 'data': student})
    except Exception as e:
        return JsonResponse({'code': 0, 'message': "删除数据库异常，请联系管理员！"})

def delete_students(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 遍历传递的集合
        for item in data['students']:
            # 查询学生信息
            obj_student = Student.objects.get(sno=item['sno'])
            # 删除数据
            obj_student.delete()
        obj_students = Student.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        student = list(obj_students)
        return JsonResponse({'code': 1, 'data': student})
    except Exception as e:
        return JsonResponse({'code': 0, 'message': "删除数据异常，请联系管理员！"})
def upload_file(request):
#     接受上传文件
    rev_file=request.FILES.get('file_name')
    if not rev_file:
        return  JsonResponse({'code':0,'msg':'图片不存在'})
    #     获得一个唯一的名字：uuid+哈希
    new_name=get_random_str()
    #准备写入的URL
    file_path=os.path.join(settings.MEDIA_ROOT,new_name+os.path.splitext(rev_file.name)[1])
    #写入本地磁盘
    try:
        #xieru
        f=open(file_path,'wb')
        for i in rev_file.chunks():
            f.write(i)
        f.close()
        return JsonResponse({'code':1,'name':new_name+os.path.splitext(rev_file.name)[1]})
    except Exception as e:
        return JsonResponse({'code':0,'msg':str(e)})


def get_random_str():
    #获取UUID随机数
    uuid_val=uuid.uuid4()
    #获取uuid的随机字符串
    uuid_str=str(uuid_val).encode('utf-8')
    #获取MD5实例
    md5=hashlib.md5()
    #拿去md5摘要
    md5.update(uuid_str)
    #返回固定长度的字符串
    return md5.hexdigest()


def import_Excel(request):
    # 从Excel导入数据
    rev_file = request.FILES.get('file_name')
    if not rev_file:
        return JsonResponse({'code': 0, 'msg': 'excel不存在'})
    #     获得一个唯一的名字：uuid+哈希
    new_name = get_random_str()
    # 准备写入的URL
    file_path = os.path.join(settings.MEDIA_ROOT, new_name + os.path.splitext(rev_file.name)[1])
    # 写入本地磁盘
    try:
        # xieru
        f = open(file_path, 'wb')
        for i in rev_file.chunks():
            f.write(i)
        f.close()
        return JsonResponse({'code': 1, 'name': new_name + os.path.splitext(rev_file.name)[1]})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': str(e)})